from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


class Profile(models.Model):
    """用户资料模型，扩展User模型存储额外信息"""
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True, default=None)
    phone = models.CharField(max_length=15, null=True, blank=True)
    
    class Meta:
        verbose_name = '用户资料'
        verbose_name_plural = '用户资料'
    
    def __str__(self):
        return f'{self.user.username}的资料'


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    """当用户创建时自动创建对应的Profile记录"""
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    """当用户保存时自动保存对应的Profile记录"""
    try:
        instance.profile.save()
    except Profile.DoesNotExist:
        # 如果Profile不存在（比如在模型创建前的用户），创建一个
        Profile.objects.create(user=instance)
